from apscheduler.schedulers.background import BackgroundScheduler

from client.redis_client import r
from utils.command_util import send_set_device_config


def job_location():
    raw_data = r.hgetall('diff_15')  # 返回字典格式：{b'field1': b'value1', ...}

    # 解码 bytes 为字符串（假设存储内容为 UTF-8 编码）
    decoded_data = {
        field.decode('utf-8'): value.decode('utf-8')
        for field, value in raw_data.items()
    }
    uppercase_keys = [key.upper() for key in decoded_data]
    for imei in uppercase_keys:
        data = {
            "url": "/sendDeviceInstructions",
            "body": {
                "imei": imei,
                "command": 128
            }
        }
        send_set_device_config(data)
    r.delete('diff_15')


def job_location_30():
    raw_data = r.hgetall('diff_30')  # 返回字典格式：{b'field1': b'value1', ...}
    # 解码 bytes 为字符串（假设存储内容为 UTF-8 编码）
    decoded_data = {
        field.decode('utf-8'): value.decode('utf-8')
        for field, value in raw_data.items()
    }
    uppercase_keys = [key.upper() for key in decoded_data]
    for imei in uppercase_keys:
        data = {
            "url": "/sendDeviceInstructions",
            "body": {
                "imei": imei,
                "command": 127
            }
        }
        send_set_device_config(data)
    r.delete('diff_30')


def start_l16_common_scheduler():
    scheduler = BackgroundScheduler()
    scheduler.add_job(job_location, "cron", minute="0,15,30,45")
    scheduler.add_job(job_location_30, "cron", minute="0,30")
    scheduler.start()
